<?php

/**
 * Created by PhpStorm.
 * User: zsm
 * Date: 2018/5/10
 * Time: 12:54
 */

namespace Library;
class Route
{

    public static $uri;
    protected static $c_name;
    protected static $a_name;

    public function __construct()
    {
        self::$c_name = Config('DEFAULT_CONTROLLER');
        self::$a_name = Config('DEFAULT_ACTION');
    }

    /*
     * 路由解析方法选择
     */
    public function bootstrap()
    {
        self::$uri = $_SERVER['REQUEST_URI'];
        switch (URL_MODE) {
            case 1:
                {
                    self::parseCommon();
                    break;
                }
            default:
                {
                    self::parseRewrite();
                }
        }
        self::boot();
    }

    /*
     * 普通路由解析
     */
    public static function parseCommon()
    {
        $router = isset($_GET['r']) ? explode('/', $_GET['r']) : [
            Config('DEFAULT_CONTROLLER'),
            Config('DEFAULT_ACTION')
        ];

        self::$c_name = ucfirst($router[0]);
        self::$a_name = isset($router[1]) ? strtolower($router[1]) : Config('DEFAULT_ACTION');
    }

    /*
     * URL重写路由解析
     */
    public static function parseRewrite()
    {

    }

    /*
     * 路由执行
     */
    public static function boot()
    {

        self::defineConst();
        $controller_name = 'index\\controller\\' . self::$c_name;
        $controller = new $controller_name();
        call_user_func([
            $controller,
            self::$a_name . 'Action'
        ]);
    }

    /*
     * 定义常用的全局常量
     */
    public static function defineConst()
    {
        define('CONTROLLER', strtolower(self::$c_name));
        define('ACTION', self::$a_name);
        define('__URL__', self::createUrl(self::$c_name . '/' . self::$a_name));
    }

    /**
     * 创建URL方法
     * @author zsm
     * @param string $info
     * @return string
     */
    public static function createUrl($info = '')
    {
        $url_info = explode('/', strtolower($info));
        $controller = isset($url_info[1]) ? $url_info[0] : strtolower(CONTROLLER);
        $action = isset($url_info[1]) ? $url_info[1] : $url_info[0];
        switch (URL_MODE) {
            case Config('URL_COMMON'):
                return "/index.php?r=" . $controller . '/' . $action;
            case Config('URL_REWRITE'):
                return '/' . $controller . '/' . $action;
        }
    }
}